#!/usr/bin/env python3
"""
First, a few callback functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.

Usage:
Example of a bot-user conversation using ConversationHandler.
Send /start to initiate the conversation.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""

import logging

from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update
from telegram.ext import (
    Updater,
    CommandHandler,
    MessageHandler,
    Filters,
    ConversationHandler,
    CallbackContext,
)
from bs4 import BeautifulSoup

import requests
import json
import os
agent = 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) \
        Gecko/20100101 Firefox/24.0'
headers = {'User-Agent': agent}
base = "https://www.azlyrics.com/"



def lyrics(artist, song):
    artist = artist.lower().replace(" ", "")
    song = song.lower().replace(" ", "")
    url = base+"lyrics/"+artist+"/"+song+".html"

    req = requests.get(url, headers=headers)
    soup = BeautifulSoup(req.content, "html.parser")
    lyrics = soup.find_all("div", attrs={"class": None, "id": None})
    if not lyrics:
        return {'Error': 'Unable to find '+song+' by '+artist}
    elif lyrics:
        lyrics = [x.getText() for x in lyrics]
        lyrics=str(lyrics)


        lyrics=lyrics.replace('["', "")
        lyrics=lyrics.replace('"]', "")
        lyrics=lyrics.replace("\\n", "\n")
        lyrics=lyrics.replace("\\r", "\r")
        lyrics=lyrics.replace("\'", "'")

#    return req
    return lyrics
def lyric2list(text):
  text_list=[]
  lines_list=text.split("\n")
  lines=""
  lines_test=""
  for i in lines_list:
    lines_test=lines_test+i+"\n"
    if len(lines_test)>4096:
      lines_test=""
      text_list.append(lines)
#      print(lines)
      lines=i+"\n"
      lines_test=i+"\n"
    else:
      lines=lines+i+"\n"
  text_list.append(lines)
  return text_list

# Enable logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)

logger = logging.getLogger(__name__)

ARTST, SONG = range(2)
def start(update, context):

    context.bot.send_message(chat_id=update.effective_chat.id, text=""" hi, i'm find_lyric bot
it can find lyric by song name and the artist
use /get to find lyric
""")


def get_lyric(update: Update, context: CallbackContext) -> int:
    user = update.message.from_user
    update.message.reply_text('    artist name:')

    return ARTST
def artst(update: Update, context: CallbackContext) -> int:
    user = update.message.from_user
    text = update.message.text
    context.user_data['artst'] = text
    update.message.reply_text('song name:')

    return SONG
def song(update: Update, context: CallbackContext) -> int:
    user = update.message.from_user
    text = update.message.text
    context.user_data['song'] = text
    user_data = context.user_data
    lyric=lyrics(user_data['artst'], user_data['song'])

    if len(lyric)<4096:
      update.message.reply_text(lyric)

    else:
      lyric_list=lyric2list(lyric)
      for i in lyric_list:
        update.message.reply_text(i)

    user_data.clear()

#    return DONE
    return ConversationHandler.END


#def done(update: Update, context: CallbackContext) -> int:

#    return ConversationHandler.END

def cancel(update: Update, context: CallbackContext) -> int:

    update.message.reply_text(
        'Bye! I hope we can talk again some day.',     )

    return ConversationHandler.END


def main() -> None:
    # Create the Updater and pass it your bot's token.
    try:
        telegram_token=os.environ["TELEGRAM_TOKEN"]
        webhook_url = os.environ["WEBHOOK_URL"]
    except Exception as e:
        print("cant find "+str(e)+" environmant")
        exit()


    updater = Updater(token=telegram_token, use_context=True)


    # Get the dispatcher to register handlers
    dispatcher = updater.dispatcher
    start_handler = CommandHandler('start', start)
    dispatcher.add_handler(start_handler)

    # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('get', get_lyric)],
        states={
            ARTST: [MessageHandler(Filters.text & ~Filters.command, artst)],
            SONG: [MessageHandler(Filters.text & ~Filters.command, song)],
        },
        fallbacks=[CommandHandler('cancel', cancel)],
    )

    dispatcher.add_handler(conv_handler)

    # Start the Bot
    updater.start_webhook(listen="0.0.0.0",
                          port=int(os.environ.get('PORT', 5000)),
                          url_path=telegram_token)
    updater.bot.setWebhook(webhook_url + telegram_token)


    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since

    updater.idle()


if __name__ == '__main__':
    main()
